package main

import (
	"fmt"
	"net"
	"time"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"syscall"
)

func main() {
	// if len(os.Args) < 2 {
	// 	fmt.Println("[Err] need : len(arg2)>1")
	// 	return
	// }

	// dir := os.Args[1]
	// fmt.Printf("[INFO] start file server :8080, dir=%s\n", dir)
	// go runNewFileServer("0.0.0.0:8080", dir)

	// //newServer("0.0.0.0:48080","/some/dir/"."prefix")

	if (len(os.Args)-1)%3 != 0 {
		fmt.Println("[Err] need : len(arg2)>1 && (len(args)-1)%3 == 0")
		return
	}

	fmt.Println(os.Args)

	argsLen := (len(os.Args) - 1) / 3
	for i := 0; i < argsLen; i++ {
		port := os.Args[i*2+1]
		dir := os.Args[i*2+2]
		prefix := os.Args[i*2+3]
		if prefix == "-" {
			prefix = ""
		}
		fmt.Printf("[INFO] start server :%s, dir=%s, prefix=%s\n", port, dir, prefix)
		go runNewFileServer("0.0.0.0:"+port, dir, prefix)
	}

	waitForSIG()
}

type fserver struct {
	host string
	// l    net.Listener

	//file server handler
	h http.Handler
}

func runNewFileServer(host, dir, prefix string) {
	fmt.Println("[INFO] starting to listen : ", host)

	l, _ := net.Listen("tcp", host)
	s := &fserver{
		host,
		http.StripPrefix(prefix, http.FileServer(http.Dir(dir))),
	}
	e := http.Serve(l, s)
	fmt.Printf("[E] run server(%s) err=%v", host, e)
}

func (s *fserver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	now := time.Now()
	formattedTime := now.Format("2006-01-02 15:04:05")
	str := fmt.Sprint(formattedTime," [info] ",r.RemoteAddr," method=", r.Method, " host=", r.Host, "  path=", r.URL.Path)
	fmt.Println(str)
	if strings.HasSuffix(r.URL.Path, ".mp4") {
		w.Header().Add("Content-Type", "video/mp4")
	}
	s.h.ServeHTTP(w, r)
}

func waitForSIG() {
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
	s := <-sigCh
	fmt.Printf("[I] signal:%s, Server is going to be closed\n", s.String())
}
